package com.fine.hair.comm.redis;

import com.fine.hair.comm.enums.AppType;
import com.fine.hair.comm.vo.LoginResultVo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

/**
 * <p></p>
 *
 * @author mouseyCat
 * @date 2020/9/7 21:16
 */
@Service
public class RedisService {
    @Autowired
    protected StringRedisTemplate redisTemplate;

    /**
     * 0, uid; 1, appType
     */
    private static final String KEY_USER_TOKEN = "user:token:{0}:{1}";
    private static final String KEY_WX_MP_ACCESS_TOKEN = "sys:wx_mp:token";
    private static final String KEY_WX_LITE_ACCESS_TOKEN = "sys:wx_lite:token";
    private static final String KEY_WX_MP_TICKET = "sys:wx_mp:ticket";
    /**
     * 0, uid; 1, appType
     */
    private static final String KEY_KAPTCHA_CODE = "kaptcha:{0}:{1}";

    public LoginResultVo getUserToken(AppType appType, String uid, String openId) {
        String key = MessageFormat.format(KEY_USER_TOKEN, openId, appType.getCode());
        String strVal = redisTemplate.opsForValue().get(key);
        if (strVal == null) {
            return null;
        }
        return new Gson().fromJson(strVal, LoginResultVo.class);
    }

    public void updateUserToken(AppType appType, LoginResultVo user, String openId) {
        String key = MessageFormat.format(KEY_USER_TOKEN, openId, appType.getCode());
        redisTemplate.opsForValue().set(key, new Gson().toJson(user), 365, TimeUnit.DAYS);
    }


    public String selectValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void delPvAdminToken(String key) {
        redisTemplate.delete(key);
    }

    public String getWxMpAccessToken() {
        return redisTemplate.opsForValue().get(KEY_WX_MP_ACCESS_TOKEN);
    }
}
